package com.rocky.study.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 主线程控制子线程同时开启
 * @author: rocky
 */
public class SonWaitMaster {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch star = new CountDownLatch(1);
        CountDownLatch latch = new CountDownLatch(10);

        for (int i = 0; i < 10; i++) {
            new Thread(new WorkerRunnable(star,latch,i)).start();
        }
        Thread.sleep(500L);
        star.countDown();

        long begin = System.currentTimeMillis();
        latch.await();
        long end = System.currentTimeMillis();
        System.out.println("一共耗时: " + (end - begin) + "ms");
    }

    public static class WorkerRunnable implements Runnable {

        private CountDownLatch begin;
        private CountDownLatch latch;
        private int id;

        public WorkerRunnable(CountDownLatch begin, CountDownLatch latch, int id) {
            this.begin = begin;
            this.latch = latch;
            this.id = id;
        }

        @Override
        public void run() {
            try {
                begin.await();
                System.out.println("编号: " + id + "开始执行,开始时间" + " " +  System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            runWork();
        }

        public void runWork() {
            try {
                TimeUnit.MILLISECONDS.sleep(500L);
                System.out.println("=== 编号:" + id + "  执行结束");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }
    }
}
